package com.gxa.eshop.portal.interceptor;

import com.gxa.eshop.core.exception.BusinessException;
import com.gxa.eshop.core.pojo.User;
import com.gxa.eshop.core.utils.JsonUtils;
import com.gxa.eshop.portal.thread.UserThreadLocal;
import org.springframework.lang.Nullable;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;

//拦截器使用策略
//1. 实现HandlerInterceptor接口
public class TokenInterceptor implements HandlerInterceptor {

    // 2.重写方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //拦截用户, 判断token
        // 通过header获取token的内容
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            // 如果token为空值, 直接拦截
            throw new BusinessException("token不能为空值");
        }

        // token存在, 进行token校验
        // 通过RestTemplate向sso服务器发起请求
        RestTemplate restTemplate = new RestTemplate();
        URI uri = new URI("http://localhost:8090/user/valuedateToken");
        // 参数
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("token",token);
        String userBeanString  = restTemplate.postForObject(uri, paramMap, String.class);
        System.out.println("userBeanString在redis = " + userBeanString);

        //把json字符串转换为User对象
        User user = JsonUtils.jsonToObject(userBeanString, User.class);
        if(user== null){
            // 否则拦截
            return false;
        }
        // 把User对象放在当前线程上
        UserThreadLocal.set(user);
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
